<?php
declare (strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use think\Exception;
use think\facade\Cache;
use think\facade\Event;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();

        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,is_active,team_total,team_id');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,team_total,team_id');
    }

    public static function generate(int $new_uid, $new_code, int $parentId, string $parentCode): bool
    {
        try {
            parent::create([
                'uid' => $parentId,
                'code' => $parentCode,
                'algebra' => 1,
                'new_uid' => $new_uid,
                'new_code' => $new_code,
            ]);
            $time = time();

            parent::where('new_uid', $parentId)
                ->field('uid,code,algebra + 1 as algebra,' . $time . ' as create_time,' . $time . ' as update_time,' . $new_uid . ' as new_uid,"' . $new_code . '" as new_code')
                ->selectInsert([
                    'uid',
                    'code',
                    'algebra',
                    'create_time',
                    'update_time',
                    'new_uid',
                    'new_code',
                ], (new static())->getName());

            return true;
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }

    }

    public static function Referrer($uid, $p_id)
    {
        $p_user = User::where('id', $p_id)->field('id,nickname,code')->find();//推荐人
        User::update(['parent_id' => $p_user->id, 'parent_name' => $p_user->nickname, 'parent_code' => $p_user->code], ['id' => $uid]);//修改推荐人

        $team_list = parent::where('uid', $uid)->column('new_uid');//获取团队
        $team_list[] = $uid;
        parent::whereIn('new_uid', $team_list)->update(['delete_time' => time()]);//删除旧推荐关系

        $user = User::whereIn('id', $team_list)->field('id,code,parent_id,parent_code')->order('id', 'asc')->select();
        foreach ($user as $k => $v) {
            (new Relation())->generate($v->id, $v->code, $v->parent_id, $v->parent_code);
        }
    }

    /**
     * @param $uid
     * @param $total
     * 原点 2023年7月12日14:16:53 团队奖
     */
    public static function teamBonus($uid, $total, $is_old = 0)
    {
        $list = parent::with('user')->where('new_uid', $uid)
            ->field('id,uid,algebra')->order('algebra', 'asc')->select();
        $poor = 0;
        $level_id = 0;
        $expendTotal = 0;
        $flat = 0;
        $flat_open = true;
        $flat_amount = 0;
        foreach ($list as $item) {
            //团队奖
            $level = UserTeam::where('id', $item->user->team_id)->find();
            if (empty($level)) continue;
            if ($item->user->team_id > $level_id && $level->tp > $poor) {
                $amount = UserRelease::release($item->uid, round($total * ($level->tp - $poor), 2),
                    $uid, '团队加速释放', 2, $is_old);
                $expendTotal += $amount;
                $poor = $level->tp;
                $level_id = $item->user->team_id;
                $flat = $item->user->team_id;
                $flat_open = true;
                $flat_amount = $amount;
            } else {
                if ($item->user->team_id == $flat && $flat_open) {
                    $amount = UserRelease::release($item->uid,
                        round($flat_amount * $level->flat_tp, 2),
                        $uid, '平级加速释放', 3, $is_old);
                    $expendTotal += $amount;
                    $flat_open = false;
                }
            }
        }
        if ($expendTotal > 0) {
            Event::trigger('Statistics', ['key' => 'expend', 'value' => $expendTotal]);
        }
    }

    /**
     * @param $uid
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid)
    {
        $list = parent::where('new_uid', $uid)
            ->order('algebra', 'asc')
            ->column('uid');
        array_unshift($list, $uid);
        foreach ($list as $item) {
            $curUser = User::where('id', $item)->findOrEmpty();
            if ($curUser->isEmpty()) continue;
            $teamLevels = UserTeam::where('id', '>', $curUser->team_id)->select();
            foreach ($teamLevels as $next) {
                switch ($next->id) {
                    case 1:
                    case 2:
                    case 3:
                        if (($curUser->my_total + $curUser->team_total) >= $next->consume_amount) {
                            User::where('id', $curUser->id)->update(['team_id' => $next->id]);
                            $curUser->team_id = $next->id;
                        }
                        break;
                    default:
                        if ($curUser->team_id > 0) {
                            $directNums = User::where('parent_id', $item)
                                ->where('team_id', $curUser->team_id)
                                ->count();
                            if ($directNums >= $next->superior_num) {
                                User::where('id', $curUser->id)->update(['team_id' => $next->id]);
                                $curUser->team_id = $next->id;
                            }
                        }
                        break;
                }
            }
        }
    }
}
